package org.pdai.basic.reflect;

import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReflectExample {

    public static void testMethod() throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        Class<?> clazz = TestClass.class;
        Method[] methods = clazz.getMethods();
        System.out.println("getMethods获取的方法：");
        for (Method m : methods) {
            System.out.println(m);
        }

        Method[] declaredMethods = clazz.getDeclaredMethods();
        System.out.println("\ngetDeclaredMethods获取的方法：");
        for (Method m : declaredMethods) {
            System.out.println(m);
        }

        Object object = clazz.newInstance();
        Method method = clazz.getMethod("add", int.class, int.class);
        Object result = method.invoke(object, 1, 4);
        System.out.println("\nresult = " + result);

//        Method method1 = clazz.getDeclaredMethod("test");
//        method1.invoke(object);
    }

    public static void testArray() throws ClassNotFoundException {
        Class<?> clazz = Class.forName("java.lang.String");
        Object array = Array.newInstance(clazz, 25);
        Array.set(array, 0, "hello");
        Array.set(array, 1, "world");
        System.out.println("Array.get(array, 1) = " + Array.get(array, 1));
    }

    public static void main(String[] args) throws Exception {
        testArray();
    }
}

class TestClass {
    public final int value = 3;
    public int add(int a, int b) {
        return a + b;
    }
    public int sub(int a, int b) {
        return a - b;
    }
    private void test() {
        System.out.println("private test method");
    }
}